<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <button class="back-arrow" @click="goBack"></button>
      <p>商家信息</p>
    </header>

    <!-- 商家logo部分 -->
    <div class="business-logo">
      <img :src="business.businessImg">
    </div>

    <!-- 商家信息部分 -->
    <div class="business-info">
      <h1>{{ business.businessName }}</h1>
      <p>&#165;{{ business.starPrice }}起送 &#165;{{ business.deliveryPrice }}配送</p>
      <p>{{ business.businessExplain }}</p>
    </div>

   <ul class="food">
     <li v-for="(item, index) in foodArr" :key="item.id" class="food-list-item">
       <div class="food-left">
         <img :src="item.foodImg" class="food-image">
         <div class="food-info">
           <h3>{{ item.foodName }}</h3>
           <p>{{ item.foodExplain }}</p>
           <p>&#165;{{ item.foodPrice }}</p>
         </div>
       </div>
       <div class="food-actions">
         <button @click="editFood(item.foodId)" class="button-style">编辑</button>
         <button @click="deleteFood(item.foodId)" class="button-style cancel-button">删除</button>
       </div>
     </li>
   </ul>
       <!-- 添加食品的表单 -->
       <div class="add-food-form" v-if="showAddFoodForm">
         <form class="form-style" @submit.prevent="addFood">
           <input class="input-style" v-model="newFood.foodName" placeholder="食品名称" required>
           <input class="input-style" v-model="newFood.foodExplain" placeholder="食品描述" required>
           <input class="input-style" v-model="newFood.foodPrice" type="number" placeholder="食品价格" required>
           <input class="input-style" type="file" @change="handleFileChange" placeholder="上传食品图片" required>
           <button type="submit" class="button-style submit-button-style">确认添加</button>
           <button @click="showAddFoodForm = false" class="button-style cancel-button">取消</button>
         </form>
       </div>
       
       <!-- 编辑食品的表单 -->
       <div class="edit-food-form" v-if="showEditFoodForm">
         <form class="form-style" @submit.prevent="updateFood">
           <input class="input-style" v-model="currentEditFood.foodName" placeholder="食品名称" required>
           <input class="input-style" v-model="currentEditFood.foodExplain" placeholder="食品描述" required>
           <input class="input-style" v-model="currentEditFood.foodPrice" type="number" placeholder="食品价格" required>
           <input class="input-style" type="file" @change="handleFileChangeEdit" placeholder="上传食品图片" required>
           <button type="submit" class="button-style submit-button-style">更新食品</button>
           <button @click="showEditFoodForm = false" class="button-style cancel-button">取消</button>
         </form>
       </div>
   
       <!-- 添加食品的按钮 -->
       <button class="button-style add-food-button" @click="showAddFoodForm = true">添加食品</button>
     </div>
   </template>
<script>
import request from '../request.js';
export default {
  name: 'food',
  data() {
    return {
      businessId: "",
      business: {},
      foodArr: [],
	   showAddFoodForm: false,
	      newFood: {
	        foodName: '',
	        foodExplain: '',
	        foodPrice: null,
	        foodImg: '',
	      },
      food:{},
	  currentEditFood: {
		  foodName: '',
		  foodExplain: '',
		  foodPrice: null,
		  foodImg: '',
	  }, // 新增属性
	     showEditFoodForm: false, // 控制编辑表单的显示
    }
  },
  created() {
    this.business = this.$getSessionStorage('businesser');
    

    // 根据businessId查询所属食品信息
    request.get(`foods/businesses/${this.business.businessId}`).then(response => {
      this.foodArr = response.data;
	  this.food    = response.data;
    }).catch(error => {
      console.error(error);
    });
	
  },
  methods: {
    goBack() {
      console.log('Trying to go back...');
      this.$router.go(-1); // 相当于浏览器的后退操作
	  
    },
	compressImage(file, maxSize) {
	    return new Promise((resolve, reject) => {
	      const reader = new FileReader();
	      reader.onload = (e) => {
	        const img = new Image();
	        img.onload = () => {
	          const canvas = document.createElement('canvas');
	          const ctx = canvas.getContext('2d');
	          const maxSizeMB = maxSize / 1024 / 1024; // 将KB转换为MB
	          const width = img.width;
	          const height = img.height;
	
	          // 设置canvas大小
	          canvas.width = width;
	          canvas.height = height;
	
	          // 压缩图片
	          ctx.drawImage(img, 0, 0, width, height);
	          const dataUrl = canvas.toDataURL('image/jpeg', 0.6); // 质量参数可以调整
	          const blob = dataURLToBlob(dataUrl);
	
	          // 创建新的File对象
	          const newFile = new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() });
	          if (newFile.size <= maxSize) {
	            resolve(newFile);
	          } else {
	            reject('Image compression did not reduce the file size enough.');
	          }
	        };
	        img.onerror = (error) => {
	          reject(error);
	        };
	        img.src = e.target.result;
	      };
	      reader.onerror = (error) => {
	        reject(error);
	      };
	      reader.readAsDataURL(file);
	    });
	  },
	handleFileChange(event) {
	  const file = event.target.files[0];
	  if (file) {
	    this.compressImage(file, 350 * 1024) // 350KB
	      .then((compressedFile) => {
	        const reader = new FileReader();
	        reader.onload = (e) => {
	          this.newFood.foodImg = e.target.result;
	        };
	        reader.readAsDataURL(compressedFile);
	      })
	      .catch((error) => {
	        console.error('Error compressing image:', error);
	        this.alertMessage = 'Error compressing image.';
	        this.alertVisible = true;
	      });
	  }
	},
	   handleFileChangeEdit(event) {
	     const file = event.target.files[0];
	     if (file) {
	       this.compressImage(file, 350 * 1024) // 350KB
	         .then((compressedFile) => {
	           const reader = new FileReader();
	           reader.onload = (e) => {
	             this.currentEditFood.foodImg = e.target.result;
	           };
	           reader.readAsDataURL(compressedFile);
	         })
	         .catch((error) => {
	           console.error('Error compressing image:', error);
	           this.alertMessage = 'Error compressing image.';
	           this.alertVisible = true;
	         });
	     }
	   },
	async addFood() {
	  try {
	    // 发送POST请求，添加新食品
	    const response = await request.post('/foods', this.$qs.stringify({
	      foodImg: this.newFood.foodImg,
	      foodName: this.newFood.foodName,
	      foodExplain: this.newFood.foodExplain,
	      foodPrice: this.newFood.foodPrice,
		  businessId:this.business.businessId
	    }));
	    await request.get(`foods/businesses/${this.business.businessId}`).then(response => {
	      this.foodArr = response.data;
	      this.food    = response.data;
	    }).catch(error => {
	      console.error(error);
	    });
	    // 将服务器返回的新食品数据添加到foodArr数组中
	     this.foodArr.push(response.data);
	
	    // 清空表单并关闭添加食品的表单
	    this.newFood = { foodName: '', foodExplain: '', foodPrice: null, foodImg: '' };
	    this.showAddFoodForm = false;
		// 刷新页面
		    this.$router.go(0);
	  } catch (error) {
	    // 捕获并处理可能出现的错误
	    console.error('Error adding food:', error);
	  }
	},
	editFood(foodId) {
	  const index = this.foodArr.findIndex(item => item.foodId === foodId);
	  if (index !== -1) {
	    this.currentEditFood = Object.assign({}, this.foodArr[index]); // 复制当前食品数据
	    this.showEditFoodForm = true; // 显示编辑表单
	  } else {
	    console.error('Food not found');
	  }
	},
	async updateFood() {
	  try {
	    const index = this.foodArr.findIndex(item => item.foodId === this.currentEditFood.foodId);
	    if (index !== -1) {
	      const response = await request.put(`/foods/${this.currentEditFood.foodId}`, this.$qs.stringify({
	        foodImg: this.currentEditFood.foodImg,
	        foodName: this.currentEditFood.foodName,
	        foodExplain: this.currentEditFood.foodExplain,
	        foodPrice: this.currentEditFood.foodPrice
	      }));
	
	      await request.get(`foods/businesses/${this.business.businessId}`).then(response => {
	        this.foodArr = response.data;
	        this.food    = response.data;
	      }).catch(error => {
	        console.error(error);
	      });
	      this.showEditFoodForm = false;
	    } else {
	      console.error('Food not found');
	    }
	  } catch (error) {
	    console.error('Error updating food:', error);
	  }
	},
	deleteFood(foodId) {
	  try {
		request.delete(`/foods/${foodId}`);
	    this.foodArr = this.foodArr.filter(item => item.foodId !== foodId);
	  } catch (error) {
	    console.error('Error deleting food:', error);
	  }
	},
  }
}
function dataURLToBlob(dataUrl) {
  const byteString = atob(dataUrl.split(',')[1]);
  const mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}
</script>

<style scoped>
  /****************** 总容器 ******************/
  .wrapper {
    width: 100%;
    height: 100%;
  }

  /****************** 返回键 ******************/
  .back-arrow {
    position: fixed;
    left: 2.5vw;
    top: 2.5vw;
    width: 8vw;
    height: 8vw;
    background-color: rgba(0, 151, 255, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    border: none;
    transition: background-color 0.3s ease;
  }

  .back-arrow::before {
    content: '\f053';
    font-family: 'FontAwesome';
    font-size: 5vh;
    color: #fff;
    transition: color 0.3s ease;
  }

  .back-arrow:hover::before {
    color: #0a2ddc;
  }

  .back-arrow:hover {
    background-color: rgba(0, 151, 255, 0.3);
  }

  /****************** header部分 ******************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /****************** 商家logo部分 ******************/
  .wrapper .business-logo {
    width: 100%;
    height: 35vw;
    margin-top: 12vw;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .wrapper .business-logo img {
    width: 40vw;
    height: 30vw;
    border-radius: 5px;
  }

  /****************** 商家信息部分 ******************/
  .wrapper .business-info {
    width: 100%;
    height: 20vw;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .wrapper .business-info h1 {
    font-size: 5vw;
  }

  .wrapper .business-info p {
    font-size: 3vw;
    color: #666;
    margin-top: 1vw;
  }

  /****************** 食品列表部分 ******************/
  .wrapper .food {
    width: 100%;
    padding-bottom: 14vw;
  }

  .wrapper .food li {
    width: 100%;
    box-sizing: border-box;
    padding: 2.5vw;
    user-select: none;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .food li .food-left {
    display: flex;
    align-items: center;
  }

  .wrapper .food li .food-left img {
    width: 20vw;
    height: 20vw;
  }

  .wrapper .food li .food-left .food-left-info {
    margin-left: 3vw;
  }

  .wrapper .food li .food-left .food-left-info h3 {
    font-size: 3.8vw;
    color: #555;
  }

  .wrapper .food li .food-left .food-left-info p {
    font-size: 3vw;
    color: #888;
    margin-top: 2vw;
  }
 /* 通用按钮样式 */
 .button-style {
   padding: 8px 16px; /* 减小内边距 */
   border: none;
   border-radius: 5px;
   background-color: #add8e6; /* 淡蓝色背景 */
   color: white;
   font-size: 14px; /* 减小字体大小 */
   cursor: pointer;
   transition: background-color 0.3s, box-shadow 0.3s;
   margin-right: 20px; /* 为按钮之间添加间隔 */
  
 }
  
  .button-style:hover {
    background-color: #b3e5fc; /* 鼠标悬浮时的淡蓝色 */
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  }
  
  .button-style:active {
    transform: translateY(2px); /* 点击时的视觉效果 */
  }
  
  /* 取消按钮的特殊样式 */
  .cancel-button {
    background-color: #ff6347; /* 淡红色背景用于取消按钮 */
    border: 1px solid #da190b;
  }
  
  .cancel-button:hover {
    background-color: #ff7b7b; /* 鼠标悬浮时的淡红色 */
  }
  
  /* 添加食品按钮的特殊样式 */
  .add-food-button {
    background-color: #add8e6; /* 淡蓝色背景 */
    border: 1px solid #add8e6; /* 淡蓝色边框 */
    display: flex;
    justify-content: center;
  }
  
  .add-food-button:hover {
    background-color: #b3e5fc; /* 鼠标悬浮时的淡蓝色 */
  }
  .cancel-button {
    background-color: #f44336;
    border: 1px solid #da190b;
  }
  
  .cancel-button:hover {
    background-color: #e53935;
  }
  .food-list-item {
    border: 1px solid #e0e0e0;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 10px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    transition: transform 0.3s, box-shadow 0.3s;
  }
  
  .food-list-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
  }
  
  .food-image {
    width: 100px;
    height: 100px;
    border-radius: 5px;
    object-fit: cover;
  }
  
  .food-info {
    flex-grow: 1;
    padding-left: 20px;
  }
  
  .food-info h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
  
  .food-info p {
    margin: 5px 0;
    font-size: 14px;
    color: #666;
  }
  /* 表单样式 */
  .form-style {
    background-color: #f7f7f7;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    margin-top: 20px;
  }
  
   /* 输入框样式 */
    .input-style {
      width: calc(100% - 20px);
      padding: 10px;
      margin-top: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 16px;
      box-sizing: border-box;
      transition: border-color 0.3s, box-shadow 0.3s;
    }
  
    .input-style:focus {
      border-color: #add8e6;
      box-shadow: 0 0 8px rgba(173, 216, 230, 0.5);
    }
  
    /* 表单样式 */
    .form-style {
      background-color: #f7f7f7;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      margin-top: 20px;
    }
  
    /* 文件输入样式 */
    input[type="file"] {
      width: 100%;
      padding: 10px;
      margin-top: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 16px;
      box-sizing: border-box;
      transition: border-color 0.3s, box-shadow 0.3s;
    }
  
    input[type="file"]:focus {
      border-color: #add8e6;
      box-shadow: 0 0 8px rgba(173, 216, 230, 0.5);
    }
</style>